package com.game.service.app;

import org.apache.commons.codec.binary.Base64;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;

public class LoadUserImageHead {
    ILoadListener mILoadListener;

    public void addListener(ILoadListener mILoadListener) {
        this.mILoadListener = mILoadListener;
    }

    public void loadImageHead(String savePath, String imageUrl) {

        String imageName = imageUrl.substring(imageUrl.lastIndexOf('/') + 1);

        new Thread(() -> {

            try {
                URL url = new URL(imageUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");

                InputStream inputStream = connection.getInputStream();
                String imageHeadFilePath = savePath + imageName;
                OutputStream outputStream = Files.newOutputStream(Paths.get(imageHeadFilePath));
                System.out.println("地址:" + imageHeadFilePath);

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                String ImageBase64 = "data:image/jpg;base64," + convertToBase64(imageHeadFilePath);
                mILoadListener.loadSuccess(ImageBase64);


                outputStream.close();
                inputStream.close();
                connection.disconnect();

                System.out.println("Image downloaded successfully.");
            } catch (Exception e) {
                //  e.printStackTrace();
                mILoadListener.error(e.toString());
            }

        }).start();
    }

    public interface ILoadListener {
        void loadSuccess(String imageBase64);

        void error(String e);
    }

    public static String convertToBase64(String imagePath) throws IOException {
        InputStream imageInputStream = Files.newInputStream(Paths.get(imagePath));
        byte[] imageBytes = new byte[imageInputStream.available()];
        imageInputStream.read(imageBytes);
        imageInputStream.close();

        return Base64.encodeBase64String(imageBytes);
    }


}